<template>
  <div class="image-container">
    <a-spin :spinning="isLoading && !url.length">
      <img
        ref="imgRef"
        :src="src"
        :width="width"
        :height="height"
        :alt="alt"
      />
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { imageProps } from 'ant-design-vue/es/vc-image/src/Image'

const props = defineProps({
  ...imageProps(),
  width: {
    type: Number,
  },
  height: {
    type: Number,
  },
  preview: {
    type: Boolean,
    default: false
  },
  alt: {
    type: String,
    default: ''
  },
})

const url = ref(''); //存储图片地址，用于判断图片是否加载成功
const isLoading = ref(false); //是否显示加载状态
const loadTimer = ref(); //加载图片的定时器
const imgRef = ref();

onMounted(() => {
  loadImage();
})

onBeforeUnmount(() => {
  if (loadTimer.value) {
    clearTimeout(loadTimer.value);
  }
})

const loadImage = () => {
  // 设置短暂延迟后显示加载状态
  loadTimer.value = setTimeout(() => {
    if(!isLoading.value) {
      isLoading.value = true;
    }
  }, 300);
  // 加载图片
  imgRef.value.src = props.src;
  imgRef.value.onerror = () => {
    //加载失败替换图片为默认图片
    imgRef.value.src = '';
    clearTimeout(loadTimer.value);
    isLoading.value = false;
  }
  imgRef.value.onload = () => {
    url.value = imgRef.value.src;
    clearTimeout(loadTimer.value);
    isLoading.value = false;
  }
}
</script>

<style scoped>
.image-container {
  position: relative;
  display: inline-block;
}
</style>